// 单例沙箱
class LegacySandBox{
  addedPropsMapInSandbox = new Map();
  modifiedPropsOriginalValueMapInSandbox = new Map();
  currentUpdatedPropsValueMap = new Map();
  proxyWindow;
  setWindowProp(prop, value, toDelete = false){
      if(value === undefined && toDelete){
          delete window[prop];
      }else{
          window[prop] = value;
      }
  }
  active(){
    // 初始化使用沙箱属性写入window
      this.currentUpdatedPropsValueMap.forEach((value, prop)=>this.setWindowProp(prop, value));
  }
  inactive(){
    // 卸载时候，重置window，并删除window多余属性
      this.modifiedPropsOriginalValueMapInSandbox.forEach((value, prop)=>this.setWindowProp(prop, value));
      this.addedPropsMapInSandbox.forEach((_, prop)=>this.setWindowProp(prop, undefined, true));
  }
  constructor(){
      const fakeWindow = Object.create(null);
      this.proxyWindow = new Proxy(fakeWindow,{
          set:(target, prop, value, receiver)=>{
              const originalVal = window[prop];
            //   window无此属性,则为新增属性
              if(!window.hasOwnProperty(prop)){
                  this.addedPropsMapInSandbox.set(prop, value);
                  // window有此属性则为修改属性
              }else if(!this.modifiedPropsOriginalValueMapInSandbox.has(prop)){
                  this.modifiedPropsOriginalValueMapInSandbox.set(prop, originalVal);
              }
              // 当前操作过的属性
              this.currentUpdatedPropsValueMap.set(prop, value);
              window[prop] = value;
          },
          get:(target, prop, receiver)=>{
              return target[prop];
          }
      });
  }
}
